package com.wzx.user.service.impl.mongo;

import com.wzx.common.pojo.resp.Result;
import com.wzx.common.util.date.DateUtil;
import com.wzx.user.dto.RelationDto;
import com.wzx.user.mapper.RelationMapper;
import com.wzx.user.mongo.MsgDto;
import com.wzx.user.mongo.SendMsg;
import com.wzx.user.mongo.SystemMsg;
import com.wzx.user.mongo.req.GetMsg;
import com.wzx.user.mongo.req.SysMsgReq;
import com.wzx.user.pojo.MsgReq;
import com.wzx.user.pojo.Relation;
import com.wzx.user.service.mongo.MsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wzx
 * @version 1.0
 * @date 2022/7/27 - 16:42
 * @description 标题
 */
@Slf4j
@Service
@Transactional
public class MsgServiceImpl implements MsgService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RelationMapper relationMapper;

    @Override
    public Result getMsgByUser(GetMsg getMsgData) {
        Query query = new Query();

        Criteria criteria = new Criteria();
        criteria.orOperator(
                Criteria.where("senderId").is(getMsgData.getReceiverId()).and("receiverId").is(getMsgData.getSenderId()),
                Criteria.where("senderId").is(getMsgData.getSenderId()).and("receiverId").is(getMsgData.getReceiverId()));
        query.addCriteria(criteria);
        //总记录数
        long total = mongoTemplate.count(query, SendMsg.class);

        //设置起始数
        query.skip((getMsgData.getPage() - 1) * getMsgData.getSize());
        //设置查询条数
        query.limit(getMsgData.getSize());

        query.with(Sort.by(Sort.Order.desc("id")));
        List<SendMsg> sendMsgs = mongoTemplate.find(query, SendMsg.class);

        float pagesFloat = (float) total / (float) getMsgData.getSize();
        long pages = (long) Math.ceil(pagesFloat);
        if (pages < getMsgData.getPage()) {
            sendMsgs = new ArrayList<>();
        }
        Collections.reverse(sendMsgs);
        return Result.successByPage(getMsgData.getPage(), getMsgData.getSize(), total, pages, sendMsgs);
    }

    @Override
    public Result getMsgBySystem(SysMsgReq sysMsgReq) {
        Query query = new Query();
        //总记录数
        long total = mongoTemplate.count(query, SystemMsg.class);
        //设置起始数
        query.skip((sysMsgReq.getPage() - 1) * sysMsgReq.getSize());
        //设置查询条数
        query.limit(sysMsgReq.getSize());

        query.with(Sort.by(Sort.Order.desc("id")));
        if (sysMsgReq.getMsgType().equals(1)) {
            //我发送的消息
            query.addCriteria(Criteria.where("senderId").is(sysMsgReq.getUserId()));
        }
        if (sysMsgReq.getMsgType().equals(2)) {
            //我接收的消息
            query.addCriteria(Criteria.where("receiverId").is(sysMsgReq.getUserId()));
        }

        List<SystemMsg> systemMsgs = mongoTemplate.find(query, SystemMsg.class);


        float pagesFloat = (float) total / (float) sysMsgReq.getSize();
        long pages = (long) Math.ceil(pagesFloat);
        return Result.successByPage(sysMsgReq.getPage(), sysMsgReq.getSize(), total, pages, systemMsgs);
    }

    @Override
    public void addFriend(SystemMsg systemMsg) {
        Query query = new Query();

        Criteria criteria = new Criteria();
        criteria.orOperator(
                Criteria.where("senderId").is(systemMsg.getSenderId())
                        .and("receiverId").is(systemMsg.getReceiverId())
                        .and("sysType").is(systemMsg.getSysType())
                        .and("state").is("0"),
                Criteria.where("receiverId").is(systemMsg.getSenderId())
                        .and("senderId").is(systemMsg.getReceiverId())
                        .and("sysType").is(systemMsg.getSysType())
                        .and("state").is("0"));
        query.addCriteria(criteria);

        /*query.addCriteria(Criteria.where("sendId").is(systemMsg.getSendId())
                .and("receiveId").is(systemMsg.getReceiveId())
                .and("sysType").is(systemMsg.getSysType())
        );*/
        if ("1".equals(systemMsg.getState())) {
            Update update = Update.update("state", systemMsg.getState());
            mongoTemplate.updateMulti(query, update, SystemMsg.class);

            Relation relation = new Relation();
            relation.setUid(systemMsg.getReceiverId());
            relation.setFid(systemMsg.getSenderId());
            //relation.setCreateTime(DateUtil.getDate());
            //设置朋友备注
            //relation.setFriendRemarks(systemMsg.getSendName());
            relation.setType("2");
            relationMapper.insert(relation);
            relation.setUid(systemMsg.getSenderId());
            relation.setFid(systemMsg.getReceiverId());
            //为朋友设置备注
            //relation.setFriendRemarks("");
            relationMapper.insert(relation);
        } else {
            Update update = Update.update("state", systemMsg.getState());
            mongoTemplate.updateMulti(query, update, SystemMsg.class);
        }

    }

    @Override
    public void cleanAllSyStemMsg(String sysIds) {
        String[] sysIdArr = sysIds.split(",");
        for (String sysId : sysIdArr) {
            Query query = Query.query(Criteria.where("id").is(Integer.parseInt(sysId)));
            mongoTemplate.remove(query, SystemMsg.class);
        }
    }

    @Override
    public List<MsgDto> getMsgs(Integer userId) {
        //1，查询关系表
        /*QueryWrapper<Relation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",userId);
        queryWrapper.and(wrapper ->wrapper.eq("type","2").or().eq("type","3"));*/
        List<RelationDto> relations = relationMapper.selectByUserId(userId);
        List<MsgDto> msgDtoList = new ArrayList<>();
        if (relations.size() == 0) {
            return msgDtoList;
        }
        List<MsgDto> collect = relations.stream().map(relation -> {
            if ("2".equals(relation.getType())) {
                //查询消息表
                Query query = new Query();
                //query.addCriteria()
                Criteria criteria = new Criteria();
                criteria.orOperator(
                        Criteria.where("senderId").is(userId + "")
                                .and("receiverId").is(relation.getUserId() + ""),
                        Criteria.where("senderId").is(relation.getUserId() + "")
                                .and("receiverId").is(userId + ""));
                query.addCriteria(criteria);
                //设置起始数
                query.skip(0);
                //设置查询条数
                query.limit(1);
                //根据id倒叙（查询最新的一条）
                query.with(Sort.by(Sort.Order.desc("id")));

                List<SendMsg> sendMsgs = mongoTemplate.find(query, SendMsg.class);
                SendMsg sendMsg = sendMsgs.get(0);
                MsgDto msgDto = new MsgDto();
                msgDto.setId(relation.getUserId());
                msgDto.setHead(relation.getHead());
                msgDto.setMsgType(sendMsg.getTypes());
                msgDto.setNickname(relation.getNickname());
                msgDto.setNews(sendMsg.getMessage());
                msgDto.setTime(sendMsg.getTime());
                msgDto.setType(2);
                msgDto.setMsgNum(0);
                return msgDto;
            }
            if ("3".equals(relation.getType())) {
                Query query = new Query();
                //设置起始数
                query.skip(0);
                //设置查询条数
                query.limit(1);
                //根据id倒叙（查询最新的一条）
                query.with(Sort.by(Sort.Order.desc("id")));
                List<SendMsg> sendMsgs = mongoTemplate.find(query, SendMsg.class, "t_groupMsg_" + relation.getUserId());

                SendMsg sendMsg = sendMsgs.get(0);
                MsgDto msgDto = new MsgDto();
                msgDto.setId(relation.getUserId());
                msgDto.setHead(relation.getHead());
                msgDto.setMsgType(sendMsg.getTypes());
                msgDto.setNickname(relation.getNickname());
                msgDto.setNews(sendMsg.getMessage());
                msgDto.setTime(sendMsg.getTime());
                msgDto.setType(3);
                msgDto.setMsgNum(0);
                return msgDto;
            }
            return null;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void cleanAllSyStemMsgAll(Integer userId) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.orOperator(
                Criteria.where("senderId").is(userId),
                Criteria.where("receiverId").is(userId));
        query.addCriteria(criteria);
        mongoTemplate.remove(query, SystemMsg.class);
    }

    @Override
    public List<MsgReq> getNotReadMsg(Integer userId, Integer pageNum) {
        log.info("用户{}，开始拉取未读消息", userId);
        //根据条件查询
        Query query = new Query();
        //query.with(Sort.by(Sort.Order.desc("id")));


        /*//直接修改状态
        Update update = new Update(); // 需要根据具体的业务场景通过newEntityList最新数据更新oldEntityList的某些数据
        update.set("state", "1");
        String collectionName = "t_not_online_" + userId;
        mongoTemplate.updateMulti(query, update, collectionName);*/

        List<MsgReq> allAndRemove = mongoTemplate.findAllAndRemove(query, MsgReq.class, "t_not_online_" + userId);
        log.info("用户拉取单聊信息成功！");

        Query queryAll = new Query();
        long count = mongoTemplate.count(queryAll, MsgReq.class, "t_not_online_group_" + userId);
        if (count == 0) {
            return allAndRemove;
        }
        Query queryByGroup = new Query();
        queryByGroup.addCriteria(Criteria.where("state").is('0'));

        long skipNum = count - pageNum;
        if (skipNum < 0) {
            skipNum = 0;
        }

        queryByGroup.skip(skipNum);
        //设置查询条数
        queryByGroup.limit(pageNum);
        List<MsgReq> queryByGroupList = mongoTemplate.find(queryByGroup, MsgReq.class, "t_not_online_group_" + userId);
        log.info("用户拉取群聊信息成功！");
        if (queryByGroupList.isEmpty()) {
            return allAndRemove;
        }
        //mongoTemplate.remove(MsgReq.class,"t_not_online_group_" + userId);
        mongoTemplate.dropCollection("t_not_online_group_" + userId);
        log.info("用户清空群聊信息成功！");

        allAndRemove.addAll(queryByGroupList);
        return allAndRemove;
        //return mongoTemplate.find(query, MsgReq.class, "t_not_online_" + userId);
    }

    @Override
    public void updateNotReadMsg(Integer userId) {
        String collectionName = "t_not_online_" + userId;
        Query query = new Query(); // 需要根据具体的业务场景来添加查询条件
        query.addCriteria(Criteria.where("state").is('0'));
        Update update = new Update(); // 需要根据具体的业务场景通过newEntityList最新数据更新oldEntityList的某些数据
        update.set("state", "1");
        mongoTemplate.updateMulti(query, update, collectionName);

    }


}
